/// Elegance控件库的按钮控件
///
/// 简洁的按钮组件，支持主题样式、不同类型和尺寸

import 'package:flutter/material.dart';

import '../../core/elegance_theme.dart';

/// 按钮样式类型枚举
enum EButtonType {
  /// 默认样式
  defaultStyle,

  /// 主要样式
  primary,

  /// 成功样式
  success,

  /// 信息样式
  info,

  /// 警告样式
  warning,

  /// 错误样式
  error,
}

/// 按钮大小类型枚举
enum EButtonSize {
  /// 大型按钮
  large,

  /// 普通按钮
  normal,

  /// 小型按钮
  mini,
}

/// 按钮外观形状枚举
enum EButtonShape {
  /// 方形按钮
  square,

  /// 圆形按钮
  circle,
}

/// 加载状态图标类型枚举
enum EButtonLoadingMode {
  /// 菊花图标
  spinner,

  /// 其他图标（可根据需要扩展）
  other,
}

/// EButton控件
class EButton extends StatefulWidget {
  /// 创建EButton控件
  const EButton({
    super.key,
    required this.text,
    this.type = EButtonType.defaultStyle,
    this.size = EButtonSize.normal,
    this.shape = EButtonShape.square,
    this.plain = false,
    this.hairline = false,
    this.disabled = false,
    this.loading = false,
    this.loadingText = '',
    this.loadingMode = EButtonLoadingMode.spinner,
    this.loadingSize = 15,
    this.icon,
    this.iconColor,
    this.throttleTime = 0,
    this.onTap,
  });

  /// 按钮文字
  final String text;

  /// 按钮样式类型
  final EButtonType type;

  /// 按钮大小
  final EButtonSize size;

  /// 按钮外观形状
  final EButtonShape shape;

  /// 是否镂空
  final bool plain;

  /// 是否显示细边框
  final bool hairline;

  /// 是否禁用
  final bool disabled;

  /// 是否显示加载中状态
  final bool loading;

  /// 加载中文字
  final String loadingText;

  /// 加载状态图标类型
  final EButtonLoadingMode loadingMode;

  /// 加载图标大小
  final double loadingSize;

  /// 按钮图标
  final IconData? icon;

  /// 图标颜色
  final Color? iconColor;

  /// 节流时间（毫秒）
  final int throttleTime;

  /// 点击事件回调
  final VoidCallback? onTap;

  @override
  EButtonState createState() => EButtonState();
}

class EButtonState extends State<EButton> {
  /// 上次点击时间，用于节流
  int _lastTapTime = 0;

  /// 是否处于悬浮状态
  bool _isHovered = false;

  /// 是否处于按下状态
  bool _isPressed = false;

  /// 处理悬浮状态变化
  void _onHoverChanged(bool isHovered) {
    if (!widget.disabled && !widget.loading) {
      setState(() {
        _isHovered = isHovered;
      });
    }
  }

  /// 处理按下状态变化
  void _onTapDown(TapDownDetails details) {
    if (!widget.disabled && !widget.loading) {
      setState(() {
        _isPressed = true;
      });
    }
  }

  /// 处理释放状态变化
  void _onTapUp(TapUpDetails details) {
    if (!widget.disabled && !widget.loading) {
      setState(() {
        _isPressed = false;
      });
    }
  }

  /// 处理取消状态变化
  void _onTapCancel() {
    if (!widget.disabled && !widget.loading) {
      setState(() {
        _isPressed = false;
      });
    }
  }

  /// 获取按钮颜色
  Color _getButtonColor(EleganceThemeData theme) {
    // 处理禁用状态
    if (widget.disabled) {
      switch (widget.type) {
        case EButtonType.primary:
          return theme.primaryColor.withOpacity(0.15);
        case EButtonType.success:
          return theme.successColor.withOpacity(0.15);
        case EButtonType.info:
          return theme.infoColor.withOpacity(0.15);
        case EButtonType.warning:
          return theme.warningColor.withOpacity(0.15);
        case EButtonType.error:
          return theme.errorColor.withOpacity(0.15);
        case EButtonType.defaultStyle:
        default:
          return theme.surfaceColor;
      }
    }

    // 处理镂空按钮的交互效果
    if (widget.plain && !widget.loading) {
      if (_isPressed) {
        // 镂空按钮点击状态：背景变深灰
        return theme.primaryDisabled;
      } else if (_isHovered) {
        // 镂空按钮悬浮状态：背景变浅灰
        return theme.surfaceColor;
      }
      // 镂空按钮正常状态：中间是空白（透明）
      return Colors.transparent;
    }

    // 非镂空状态的处理逻辑
    Color baseColor;

    switch (widget.type) {
      case EButtonType.primary:
        baseColor = theme.primaryColor;
        break;
      case EButtonType.success:
        baseColor = theme.successColor;
        break;
      case EButtonType.info:
        baseColor = theme.infoColor;
        break;
      case EButtonType.warning:
        baseColor = theme.warningColor;
        break;
      case EButtonType.error:
        baseColor = theme.errorColor;
        break;
      case EButtonType.defaultStyle:
      default:
        baseColor = theme.surfaceColor;
        break;
    }

    // 处理非镂空按钮的悬浮和点击状态的颜色变化
    if (!widget.loading && !widget.plain) {
      if (_isPressed) {
        // 点击状态：颜色加深
        return Color.lerp(baseColor, Colors.black, 0.2) ?? baseColor;
      } else if (_isHovered) {
        // 悬浮状态：颜色变浅
        return Color.lerp(baseColor, Colors.white, 0.1) ?? baseColor;
      }
    }

    return baseColor;
  }

  /// 获取按钮文字颜色
  Color _getTextColor(EleganceThemeData theme) {
    if (widget.disabled) {
      // 禁用按钮也分类型，保持与正常状态相同的颜色倾向但更淡
      switch (widget.type) {
        case EButtonType.primary:
          return theme.primaryColor.withOpacity(0.5);
          return theme.primaryColor;
        case EButtonType.success:
          return theme.successColor.withOpacity(0.5);
          return theme.successColor;
        case EButtonType.info:
          return theme.infoColor.withOpacity(0.5);
          return theme.infoColor;
        case EButtonType.warning:
          return theme.warningColor.withOpacity(0.5);
          return theme.warningColor;
        case EButtonType.error:
          return theme.errorColor.withOpacity(0.5);
          return theme.errorColor;
        case EButtonType.defaultStyle:
        default:
          return theme.textPrimaryColor.withOpacity(0.5);
          return theme.textPrimaryColor;
      }
    }

    // 镂空状态下，文字颜色与边框颜色一致
    if (widget.plain) {
      switch (widget.type) {
        case EButtonType.primary:
          return theme.primaryColor;
        case EButtonType.success:
          return theme.successColor;
        case EButtonType.info:
          return theme.infoColor;
        case EButtonType.warning:
          return theme.warningColor;
        case EButtonType.error:
          return theme.errorColor;
        case EButtonType.defaultStyle:
        default:
          return theme.textPrimaryColor;
      }
    }

    // 非镂空状态下，除了default类型外，文字颜色都是白色
    return widget.type == EButtonType.defaultStyle
        ? theme.textPrimaryColor
        : theme.textRegularColor;
    // 注意：这里使用了textRegularColor而不是白色，以确保在深色主题下文本仍然可见
  }

  /// 获取按钮边框颜色
  Color _getBorderColor(EleganceThemeData theme) {
    if (widget.disabled) {
      // 禁用状态下的边框颜色，与按钮颜色保持一致但透明度更高
      switch (widget.type) {
        case EButtonType.primary:
          return theme.primaryColor.withOpacity(0.3);
        case EButtonType.success:
          return theme.successColor.withOpacity(0.3);
        case EButtonType.info:
          return theme.infoColor.withOpacity(0.3);
        case EButtonType.warning:
          return theme.warningColor.withOpacity(0.3);
        case EButtonType.error:
          return theme.errorColor.withOpacity(0.3);
        case EButtonType.defaultStyle:
        default:
          return Colors.grey.shade300;
      }
    }

    // 镂空状态下，边框颜色与文字颜色一致
    if (widget.plain) {
      switch (widget.type) {
        case EButtonType.primary:
          return theme.primaryColor;
        case EButtonType.success:
          return theme.successColor;
        case EButtonType.info:
          return theme.infoColor;
        case EButtonType.warning:
          return theme.warningColor;
        case EButtonType.error:
          return theme.errorColor;
        case EButtonType.defaultStyle:
        default:
          return theme.textPrimaryColor;
      }
    }

    // 默认按钮也有边框
    if (widget.type == EButtonType.defaultStyle) {
      return theme.borderColor; // 颜色比背景灰一点点
    }

    return Colors.transparent;
  }

  /// 获取按钮尺寸
  Map<String, dynamic> _getButtonSize() {
    switch (widget.size) {
      case EButtonSize.large:
        return {
          'height': 48.0,
          'padding': const EdgeInsets.symmetric(horizontal: 24.0),
          'fontSize': 18.0,
        };
      case EButtonSize.mini:
        return {
          'height': 28.0,
          'padding': const EdgeInsets.symmetric(horizontal: 12.0),
          'fontSize': 14.0,
        };
      case EButtonSize.normal:
      default:
        return {
          'height': 40.0,
          'padding': const EdgeInsets.symmetric(horizontal: 20.0),
          'fontSize': 16.0,
        };
    }
  }

  /// 获取圆角值
  double _getBorderRadius(EleganceThemeData theme, double height) {
    if (widget.shape == EButtonShape.circle) {
      return height / 2;
    }
    return theme.borderRadius;
  }

  /// 处理按钮点击
  void _handleTap() {
    if (widget.disabled || widget.loading) {
      return;
    }

    // 节流处理
    final now = DateTime.now().millisecondsSinceEpoch;
    if (now - _lastTapTime < widget.throttleTime) {
      return;
    }
    _lastTapTime = now;

    widget.onTap?.call();
  }

  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    final sizeInfo = _getButtonSize();
    final height = sizeInfo['height'] as double;
    final padding = sizeInfo['padding'] as EdgeInsets;
    final fontSize = sizeInfo['fontSize'] as double;

    // 计算圆角
    final borderRadius = _getBorderRadius(theme, height);

    // 构建按钮内容
    Widget buttonContent;

    if (widget.loading) {
      // 加载中状态
      final loadingContent = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: widget.loadingSize,
            height: widget.loadingSize,
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
              valueColor: AlwaysStoppedAnimation<Color>(_getTextColor(theme)),
              backgroundColor: Colors.transparent,
            ),
          ),
          if (widget.loadingText.isNotEmpty) ...[
            const SizedBox(width: 8.0),
            Text(
              widget.loadingText,
              style: TextStyle(
                color: _getTextColor(theme),
                fontSize: fontSize,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ],
      );

      buttonContent = loadingContent;
    } else {
      // 正常状态
      final content = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (widget.icon != null) ...[
            Icon(
              widget.icon,
              size: fontSize,
              color: widget.iconColor ?? _getTextColor(theme),
            ),
            const SizedBox(width: 8.0),
          ],
          Text(
            widget.text,
            style: TextStyle(
              color: widget.disabled
                  ? Colors.grey.shade400
                  : _getTextColor(theme),
              fontSize: fontSize,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      );

      buttonContent = content;
    }

    // 构建按钮装饰
    final decoration = BoxDecoration(
      color: _getButtonColor(theme),
      border: Border.all(
        color: _getBorderColor(theme),
        width: widget.hairline ? 0.5 : 1.0,
      ),
      borderRadius: BorderRadius.circular(borderRadius),
    );

    // 构建按钮
    final button = Container(
      height: height,
      padding: padding,
      decoration: decoration,
      alignment: Alignment.center,
      child: buttonContent,
    );

    // 添加事件处理
    if (widget.onTap != null && !widget.disabled && !widget.loading) {
      return MouseRegion(
        onEnter: (_) => _onHoverChanged(true),
        onExit: (_) => _onHoverChanged(false),
        child: GestureDetector(
          onTap: _handleTap,
          onTapDown: _onTapDown,
          onTapUp: _onTapUp,
          onTapCancel: _onTapCancel,
          child: button,
        ),
      );
    }

    // 非点击状态的按钮也需要处理悬浮效果
    return MouseRegion(
      onEnter: (_) => _onHoverChanged(true),
      onExit: (_) => _onHoverChanged(false),
      child: button,
    );
  }
}

